/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.activity;

import java.util.Arrays;
import java.util.Comparator;

import org.sabayframework.activity.impl.ForkJoin;
import org.sabayframework.activity.impl.ReplicableActivity;

/**
 * Parallel merge sort example.
 * @author Alex Antonau
 * */
public final class ForkJoinSort<T> extends ForkJoin<SortData<T>, SortData<T>>{
	
	
	@SuppressWarnings("rawtypes")
	final private Comparator comparator;
	final private int sequentialThreshhold;
	
	@SuppressWarnings("rawtypes")
	public ForkJoinSort(Comparator comparator, int sequentialThreshhold) {
		super();
		this.comparator = comparator;
		this.sequentialThreshhold = sequentialThreshhold;
	}
	
	public ForkJoinSort(int sequentialThreshhold) {
		this(new Comparator<Comparable<Object>>() {
			public int compare(Comparable<Object> o1, Comparable<Object> o2) {
				return o1.compareTo(o2);
			}
		}, sequentialThreshhold);
	}
	
	public ForkJoinSort(){
		this(100000);
	}
	

	@Override
	public Object[] fork(SortData<T> data) {
		final int fromIndex = data.getStartIndex();
		final int toIndex = data.getEndIndex();
		final int len = toIndex - fromIndex;
		if(len > sequentialThreshhold){
			int middle = fromIndex + len/2;
			data.setEndIndex(middle);
			SortData<T> data2 = new SortData<T>(data.getArray(),middle, toIndex);
			return new Object[]{data, data2};
		}
		return new Object[]{data};
	}

	@SuppressWarnings("unchecked")
	@Override
	public SortData<T> process(SortData<T> r) {
		Arrays.sort(r.getArray(), r.getStartIndex(), r.getEndIndex(), comparator);
		return r;
	}

	@SuppressWarnings("unchecked")
	@Override
	public SortData<T> join(Object[] out) {
		SortData<T> r1 = (SortData<T>) out[0];
		SortData<T> r2 = (SortData<T>) out[1];
		int start = r1.getStartIndex();
		int end = r2.getEndIndex();
		int middle = r1.getEndIndex();
		if(end < middle){
			start= r2.getStartIndex();
			middle = end;
			end = r1.getEndIndex();
		}
		merge(r1.getArray(), start, middle-1, end-1, comparator);
		r1.setStartIndex(start);
		r1.setEndIndex(end);
		return r1;
	}

	@Override
	public ReplicableActivity<SortData<T>, SortData<T>> replicate() {
		return new ForkJoinSort<T>(comparator, sequentialThreshhold);
	}
	
    @SuppressWarnings({ "unchecked", "rawtypes" })
	private static void merge(final Object[] a,final int start,final int middle,final int end,final Comparator comparator){
        
        int j = middle + 1;
        if(middle == start || 
           middle == end || 
           comparator.compare(a[j - 1], a[j]) <= 0){
            //the two chunks are already ordered
            return;         
        }
        final int maxChunkIndex = middle - start;
        
        //we need to create a copy of the first array, so that we can overwrite it
        final Object[] b = new Object[maxChunkIndex + 1];
        System.arraycopy(a, start, b, 0, maxChunkIndex +1);
        int i = 0;
        
        //iterating over each position of the "new" array been created
        for(int k = start; k <= end; k++){
        	
        	//is there any element at first chunk 
        	//AND the lower element of the second chunk is lower that the lower 
        	//of the first chunk?
            if(i <= maxChunkIndex && comparator.compare(b[i], a[j]) < 0){
            	//the element from second chunk is lower 
            	//put if at the position and take it off the second chunk
                a[k] = b[i++];
            } else {
                //we reach the end of the first array
                a[k] = a[j++];
                //is there any other element at second chunk?
                if(j > end){
                    //there is only elements at the first chunk  
                    //so we need to copy the remaining of the first array to the end of the "new" array
                    System.arraycopy(b, i, a, k+1, b.length-i);
                    return;
                }
            }
        }
    }
}
